package io.persimmon.core.module.calculation.instance;

import io.persimmon.core.module.calculation.Calculation;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

public class AvgCalculation implements Calculation<Double, Number> {

    private AtomicLong sum;
    private AtomicInteger count;

    @Override
    public void accept(Number data) {
        sum.addAndGet((long) (data.doubleValue() * 10000));
        count.incrementAndGet();
    }

    @Override
    public Double calculationResult() {
        if (count.get() == 0) {
            return 0.0;
        }
        return sum.get() / (double) count.get() / 10000;
    }

    @Override
    public void clean() {
        sum.set(0);
    }
}
